package com.wan.net.session;

import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.util.concurrent.CountDownLatch;
import java.util.function.Supplier;

public interface AttributeKeys {
    /** 同服务channel唯一id */
    AttributeKey<Long> CHANNEL_ID = AttributeKey.valueOf("channel_id");
    /** 信号灯 */
    AttributeKey<CountDownLatch> SIGNAL = AttributeKey.valueOf("signal");

    static <T>void set(Channel channel,AttributeKey<T> attributeKey,T value){
        channel.attr(attributeKey).set(value);
    }

    static <T> T get(Channel channel,AttributeKey<T> attributeKey){
        return channel.attr(attributeKey).get();
    }

    static <T> T getOrSet(Channel channel, AttributeKey<T> attributeKey, Supplier<T> supplier){
        Attribute<T> attr = channel.attr(attributeKey);
        if(attr.get() != null){
            return attr.get();
        }
        T t = supplier.get();
        if(attr.compareAndSet(null,t)){
            return t;
        }
        return attr.get();
    }

}
